import sqlalchemy as sa
from sqlalchemy import orm

from formalchemyhandling.model import meta

def init_model(engine):
    """Call me before using any of the tables or classes in the model."""
    sm = orm.sessionmaker(autoflush=True, transactional=True, bind=engine)

    meta.engine = engine
    meta.Session = orm.scoped_session(sm)

# table for the orders
orders_table = sa.Table('orders', meta.metadata,
    sa.Column('id', sa.types.Integer, primary_key=True),
    sa.Column('user_id', sa.types.Integer, sa.ForeignKey('users.id'), nullable=False),
    sa.Column('quantity', sa.types.Integer, nullable=False))

class Order(object):

    def __str__(self):
        return 'Quantity: %s' % self.quantity

# table for the users
users_table = sa.Table('users', meta.metadata,
    sa.Column('id', sa.types.Integer, primary_key=True),
    sa.Column('name', sa.types.Unicode(30)))

class User(object):

    def __str__(self):
        return self.name

# mapping
orm.mapper(Order, orders_table)
orm.mapper(User, users_table,
        properties = {'orders' : orm.relation(Order, backref='user')})
